import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    squareImg:"",//方形颜色图片
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    totalCount: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    answerImg: '', //问答图片
    answerImgs:[],//问答图片数组
    isShowImg:true,//是否显示块状颜色图片
    imgs:[],//块状颜色图片
    imgsPrefix:[],//块状颜色
    missImgNames:[],//缺失椭圆图片数组所有的fileName
    answerImgIndex: 0, // 当前答题图片索引
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();

    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      totalCount:count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  getCurrentTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {topicContent,currentIndex,count} = this.data;
    // 缓存下一题图片
    let newIndex = currentIndex + 1;
    if(newIndex < count){
      util.preLoadImg(questionIndex,newIndex)
    }
    const preImgs = wx.getStorageSync('preImgs')||[];

    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const cardNumber = currentTopic.answerPictureNumber;// 全部问题数量

    // 确保 missEllipsePicture 是数组类型
    let missEllipsePicture = JSON.parse(currentTopic.missEllipsePicture);
    const missImgNames = missEllipsePicture.map(item => item.fileName);
    // console.log('缺失椭圆图片数组所有的fileName',missImgNames)
    // 随机出需要展示的缺失圆角数量 随机出 1 或者 2
    const missCount = Math.floor(Math.random() * 2) + 1;
    // 剩余展示数量
    let otherCount = cardNumber - missCount;
    // 含有椭圆的数据
    const missArray = this.getRandomElements(missEllipsePicture, missCount);
    // 剩余随机数据
    let randomColorPicture = JSON.parse(currentTopic.randomColorPicture);
    let otherArray = this.getRandomElements(randomColorPicture, otherCount);
    // 所有问题数据
    let answerImgs = [...otherArray,...missArray];
    // 打乱数组顺序
    answerImgs = this.shuffleArray(answerImgs);
    answerImgs.forEach((img, index) => {
      let imageUrl = ''
      if(img.url.startsWith("http")){
        imageUrl = img.url
      }else{
        imageUrl = util.base_url + img.url;
      }    
      const isIos =  util.checkPlatform()
      if(isIos){
        imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl
      }else{
        imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,webp'
      }
      
      answerImgs[index] = {
        ...img,
        url: imageUrl
      };
    });
    // console.log('所有问题数据answerImgs:', answerImgs)
    
    // 显示块状颜色图
    const colorCardPicture = JSON.parse(currentTopic.colorCardPicture);
    const colorCardNumber = currentTopic.colorCardNumber;
    let imgs = this.getRandomElements(colorCardPicture, colorCardNumber);
    imgs.forEach((img, index) => {
      let imageUrl = ''
      if(img.url.startsWith("http")){
        imageUrl = img.url
      }else{
        imageUrl = util.base_url + img.url;
      } 
      const isIos =  util.checkPlatform()
      if(isIos){
        imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl
      }else{
        imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,webp'
      }
    
      imgs[index] = {
        ...img,
        url: imageUrl
      };
    });
    // console.log('所有块状颜色图imgs:', imgs)
    // 提取 imgs 中每个 url 的颜色名称为新数组
    const imgsPrefix = imgs.map(item => this.extractColorNameFromUrl(item.fileName));
    // console.log('颜色名称数组imgsPrefix:', imgsPrefix);

    const blankTime = currentTopic.blankTime;//间隔时间
    const colorCardRetentionTime = currentTopic.colorCardRetentionTime;//每张图片显示时间
    const maxAnswerTime = currentTopic.maxAnswerTime;//每张问答图片显示时间
    // 块状颜色图片轮播
    setTimeout(() =>{
      this.startImageCarousel(imgs, colorCardRetentionTime, blankTime,maxAnswerTime);
    },800)


    this.setData({
      currentTopic,
      answerImgs,
      imgs,
      missImgNames,
      imgsPrefix,
      isShowImg: true, // 重置为true，显示块状颜色图片
    });
  },
  // 从数组中随机选取指定数量的元素
  getRandomElements(array, count) {
  const arrayCopy = [...array];
  const result = [];
  for (let i = 0; i < count; i++) {
    // 生成随机索引
    const randomIndex = Math.floor(Math.random() * arrayCopy.length);
    // 将随机选中的元素添加到结果数组
    result.push(arrayCopy[randomIndex]);
    // 从副本中移除已选元素，避免重复选择
    arrayCopy.splice(randomIndex, 1);
  }
  return result;
  },
  // 打乱问答图片数组顺序
  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },
  // 块状颜色图片轮播显示
  startImageCarousel(images, displayTime, blankTime,maxAnswerTime) {
    let imageIndex = 0;
    let showBlank = false;
    
    const showNextImage = () => {
      if (imageIndex < images.length) {
        if (showBlank) {
          // 显示空白
          this.setData({
            squareImg: '' // 空白方形图
          });
          showBlank = false;
          // blankTime后显示下一张图片
          setTimeout(showNextImage, blankTime);
        } else {
          // 显示图片
          this.setData({
            squareImg: images[imageIndex].url // 如果需要在方形图中也显示
          });
          imageIndex++;
          showBlank = true;
          // displayTime后显示空白
          setTimeout(showNextImage, displayTime);
        }
      } else {
         // 所有图片展示完毕，开始显示 answerImgs 中的图片
        this.showAnswerImages(maxAnswerTime);
      }
    };
    // 开始展示第一张图片
    showNextImage();
  },
  // 显示答案图片
  showAnswerImages(maxAnswerTime) {
    const { answerImgs } = this.data;
    
    // 初始化答题状态
    this.setData({
      answerImg: answerImgs[0].url,
      isShowImg: false, // 隐藏之前的块状图片
      squareImg: '', // 清空方形图
      answerImgIndex: 0, // 设置当前答题图片索引为0
      questionStartTime: new Date().getTime()
    });

    // 设置自动切换定时器
    this.setNextAnswerTimer(maxAnswerTime);
  
  },
  // 设置下一个答案图片的定时器
  setNextAnswerTimer(maxAnswerTime) {
    // 清除之前的定时器（如果存在）
    if (this.answerTimer) {
      clearTimeout(this.answerTimer);
    }

    // 设置新的定时器
    this.answerTimer = setTimeout(() => {
      this.showNextAnswerByTimer(maxAnswerTime);
    }, maxAnswerTime);
  },
  // 通过定时器显示下一张答案图片
  showNextAnswerByTimer(maxAnswerTime) {
    const { answerImgs, answerImgIndex,missImgNames } = this.data;
    const nextIndex = answerImgIndex + 1;
     // 自动记录未答题结果
    if (answerImgIndex < answerImgs.length) {
      const currentAnswerImg = answerImgs[answerImgIndex];
      const imgFileName = currentAnswerImg.fileName || 
        (currentAnswerImg.url ? currentAnswerImg.url.split('/').pop().split('?')[0] : '');
      
       // 获取正确答案
      const isInMissList = missImgNames.includes(imgFileName);
      const correctAnswer = this.getCorrectAnswer(imgFileName, isInMissList);
      
      // 使用共用方法创建并保存答题记录
      const newAnswerRecords = this.createAndSaveAnswerRecord(true, '', false, correctAnswer);
      this.setData({
        answerRecords: newAnswerRecords
      });
    }
    if (nextIndex < answerImgs.length) {
      this.setData({
        answerImgIndex: nextIndex,
        answerImg: answerImgs[nextIndex].url
      });

      // 继续设置下一个定时器
      this.setNextAnswerTimer(maxAnswerTime);
    } else {
      // 所有答案图片展示完毕
      this.setData({
        answerImg: '' // 清空答案图片
      });

      let {currentIndex,totalCount} = this.data;
      // 无论对错都增加总次数
      let countNum = currentIndex + 1;
      if (countNum >= totalCount) {
          //跳转下一题
          let questionNumber = this.data.questionIndex + 1;
          const prevInfo = wx.getStorageSync('questionInfo') || {};
          wx.setStorageSync('questionInfo', {
            ...prevInfo,
            questionNumber
          });
          util.navigateByDesc(questionNumber);
      } else {
        // 重置 isShowImg 为 true
        this.setData({
          isShowImg: true
        });
        this.getCurrentTopicData()
      }
      this.setData({
        currentIndex: countNum
      })
    }
  },
  // 用户点击按钮时显示下一张答案图片
  showNextAnswer() {
    const { answerImgs, answerImgIndex, currentTopic } = this.data;
    const nextIndex = answerImgIndex + 1;
    const maxAnswerTime = currentTopic.maxAnswerTime; // 获取最大答题时间

    // 清除当前的定时器
    if (this.answerTimer) {
      clearTimeout(this.answerTimer);
    }

    if (nextIndex < answerImgs.length) {
      this.setData({
        answerImgIndex: nextIndex,
        answerImg: answerImgs[nextIndex].url
      });

      // 重新设置定时器以继续自动播放
      this.setNextAnswerTimer(maxAnswerTime);
    } else {
      // 所有答案图片展示完毕
      this.setData({
        answerImg: '' // 清空答案图片
      });

      let {currentIndex,totalCount} = this.data;
      // 无论对错都增加总次数
      let countNum = currentIndex + 1;
      if (countNum >= totalCount) {
          //跳转下一题
          let questionNumber = this.data.questionIndex + 1;
          const prevInfo = wx.getStorageSync('questionInfo') || {};
          wx.setStorageSync('questionInfo', {
            ...prevInfo,
            questionNumber
          });
          util.navigateByDesc(questionNumber);
      } else {
        // 重置 isShowImg 为 true
        this.setData({
          isShowImg: true
        });
        this.getCurrentTopicData()
      }
      this.setData({
        currentIndex: countNum
      })
    }
  },



  // 提取块状颜色数组中的颜色名称
  extractColorNameFromUrl(url) {
    if (!url) return '';
    try {
      // 获取URL中最后一部分（文件名）
      const fileName = url.split('/').pop().split('?')[0]; // 移除查询参数
      // 移除文件扩展名
      const nameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
      // 提取颜色名称部分（处理 colorname-1_20221002224242A196 这种格式）
      const colorName = nameWithoutExt.split(/[-_]/)[0];
      return colorName;
    } catch (e) {
      console.error('解析颜色名称失败:', e);
      return '';
    }
  },
  // 点击按钮
  onTap(e){
    let name = e.currentTarget.dataset.name;
    if(name == 'yes'){
      this.checkAnswer('yes');
    } else if(name == 'no'){
      this.checkAnswer('no');
    } else {
      this.checkAnswer('empty');
    }
  },
  // 提取正确答案的方法
  getCorrectAnswer(imgFileName, isInMissList) {
    const { imgsPrefix } = this.data;
    
    // 如果在缺失列表中，正确答案应该是"empty"
    if (isInMissList) {
      return 'empty';
    }
    
    // 如果不在缺失列表中，需要判断颜色是否匹配
    const color = this.extractColorNameFromUrl(imgFileName);
    
    // 如果颜色匹配imgsPrefix中的颜色，正确答案是"yes"，否则是"no"
    if (color && imgsPrefix.includes(color)) {
      return 'yes';
    } else {
      return 'no';
    }
  },
  // 检查答案
  checkAnswer(userAnswer) {
    const { answerImgs, answerImgIndex, missImgNames } = this.data;
    
    // 获取当前答题图片
    const currentAnswerImg = answerImgs[answerImgIndex];
    if (!currentAnswerImg) return;
    
    // 获取文件名
    const imgFileName = currentAnswerImg.fileName || 
      (currentAnswerImg.url ? currentAnswerImg.url.split('/').pop().split('?')[0] : '');
    
    // 判断是否在缺失图片列表中
    const isInMissList = missImgNames.includes(imgFileName);
    
    // 获取正确答案
    const correctAnswer = this.getCorrectAnswer(imgFileName, isInMissList);
    
    let isCorrect = false;
    
    // 判断用户答案是否正确
    if (userAnswer === correctAnswer) {
      isCorrect = true;
    }
    
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, userAnswer, isCorrect, correctAnswer);
    this.setData({
      answerRecords: newAnswerRecords
    });
    
    // 显示下一张答题图片
    this.showNextAnswer();
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '', isRight = false, correctOption = '') {
    const {currentIndex, questionStartTime, topicContent} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    
    // 判断是否正确（超时视为错误）
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: correctOption, // 添加正确答案
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },
  // 页面卸载时清除定时器
  onUnload() {
    if (this.answerTimer) {
      clearTimeout(this.answerTimer);
    }
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }

})